package com.gadberry.utility.expression.function;
import java.util.Iterator;
import java.util.List;

import com.gadberry.utility.algorithm.Algorithm;
import com.gadberry.utility.expression.Argument;
import com.gadberry.utility.expression.Expression;
import com.gadberry.utility.expression.Function;
import com.gadberry.utility.expression.InvalidArgumentsException;

/**
 * Calculates the value of one number raised to any power. The ^ symbol
 * also does the same thing. <br>
 * 
 * @author Peter Lager
 *
 */
public class PowerFunction extends Function{

	public PowerFunction(Expression expression) {
		super(expression);
	}

	@Override
	public Argument resolve(Algorithm algor) {
		double n = 0, p = 0;
		Iterator<Argument> iter = getArguments().iterator();
		n = iter.next().toDouble();
		p = iter.next().toDouble();
		return new Argument(new Double(Math.pow(n, p)), getResolver());
	}

	@Override
	protected void checkArgs(List<Argument> args)
	throws InvalidArgumentsException {
		if (args.size() != 2) {
			throw new InvalidArgumentsException(
			"PowerOperator requires two doubles.  Wrong number of arguments provided.");
		}
		for (Argument arg : args) {
			if(arg.isNull()) {
				throw new InvalidArgumentsException(
						"PowerOperator cannot accept null arguments.  The argument provided is null.");
			} else if (!arg.isDouble()) {
				throw new InvalidArgumentsException(
						"MaxOperator only accepts doubles.  Wrong type of arguments provided.  Arg: " + arg.toString());
			}

		}
	}

}


